<template>
  <div class="subscriptions-container el-row">
    <!-- 移除左侧导航菜单 -->
    <!-- <el-col :xs="24" :sm="4" :md="3" class="profile-sidebar">
      ...
    </el-col> -->

    <!-- 右侧内容区域 - 调整栅格占据整个宽度 -->
    <el-col :xs="24" :sm="24" :md="24" class="profile-content">
      <div class="content-wrapper">
        <div class="section-header">
          <h3>我的订阅</h3>
          <el-select v-model="sortBy" class="sort-select" size="small">
            <el-option label="最新发布" value="latest" />
            <el-option label="最多观看" value="popular" />
          </el-select>
        </div>

        <div class="video-content" v-loading="loading">
          <div v-if="videos.length === 0 && !loading" class="empty-state"> <!-- 仅在非加载状态下显示空状态 -->
            <el-empty :description="emptyDescription" />
            <el-button type="primary" @click="goToTrending" v-if="!hasSubscriptions">
              发现更多内容
            </el-button>
          </div>

          <div v-else class="video-grid">
            <div v-for="video in videos" :key="video._id" class="video-card" @click="goToVideo(video._id)">
              <div class="thumbnail">
                <img :src="video.thumbnail" :alt="video.title">
                <span class="duration">{{ formatDuration(video.duration) }}</span>
              </div>
              <div class="video-info">
                <div class="channel-avatar">
                  <!-- 修改：仅在频道有头像时显示头像 -->
                  <el-avatar v-if="video.channel?.avatar" :size="36" :src="video.channel.avatar">
                  </el-avatar>
                  <!-- 可以选择添加一个占位符或图标 -->
                  <!-- <el-avatar v-else :size="36"><User /></el-avatar> -->
                </div>
                <div class="video-details">
                  <h4 class="title">{{ video.title }}</h4>
                  <div class="channel-name">
                    {{ video.channel?.name || '未知频道' }} <!-- 添加空值处理 -->
                  </div>
                  <div class="stats">
                    <span>{{ formatViews(video.views) }}次观看</span>
                    <span class="dot">•</span>
                    <span>{{ formatDate(video.createdAt) }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="load-more" v-if="hasMore && !loading && videos.length > 0"> <!-- 仅在有更多且非加载状态且已有视频时显示 -->
            <el-button :loading="loadingMore" @click="loadMore">加载更多</el-button>
          </div>
        </div>
      </div>
    </el-col>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import axios from '@/services/axios'
import { ElMessage, ElEmpty, ElButton, ElSelect, ElOption, ElAvatar, ElIcon, ElMenu, ElMenuItem, ElCol } from 'element-plus' // 补全导入
import { formatDuration, formatViews, formatDate } from '@/utils/formatters';
// 移除不再需要的图标导入
// import { VideoCamera, Document, Setting, Star } from '@element-plus/icons-vue'

const router = useRouter()

// 状态变量
const loading = ref(false)
const loadingMore = ref(false)
const hasMore = ref(true)
const sortBy = ref('latest')
const page = ref(1)
const pageSize = 12 // 增加每页加载数量
const error = ref(null); // 添加 error 状态
const totalVideos = ref(0); // 添加 totalVideos 状态
const currentPage = ref(1); // 添加 currentPage 状态

// 数据列表
const videos = ref([])

// 计算属性
const hasSubscriptions = computed(() => true) // 假设用户总是有订阅
const emptyDescription = computed(() => {
  return '暂无订阅内容'
})

// 获取视频列表
const fetchSubscribedVideos = async (loadMoreMode = false) => {
  if (!loadMoreMode) {
    loading.value = true;
    page.value = 1; // 重置页码
    videos.value = []; // 清空现有视频
  } else {
    loadingMore.value = true;
  }
  error.value = null;
  try {
    const params = {
      page: page.value,
      limit: pageSize,
      sort: sortBy.value
    };
    const response = await axios.get('/api/videos/subscriptions', { params });
    const newVideos = response.data.videos || [];
    if (loadMoreMode) {
      videos.value = [...videos.value, ...newVideos];
    } else {
      videos.value = newVideos;
    }
    totalVideos.value = response.data.total || 0;
    hasMore.value = videos.value.length < totalVideos.value;
    if (newVideos.length > 0) {
      page.value++; // 只有成功加载到数据才增加页码
    }
  } catch (err) {
    console.error('获取订阅视频失败:', err);
    error.value = err.response?.data?.error || '获取订阅视频失败';
    ElMessage.error(error.value); // 显示错误信息
  } finally {
    loading.value = false;
    loadingMore.value = false;
  }
};

// 加载更多
const loadMore = () => {
  fetchSubscribedVideos(true) // 传入 true 表示加载更多模式
}

// 跳转到视频详情页
const goToVideo = (videoId) => {
  router.push(`/video/${videoId}`)
}

// 跳转到热门页面
const goToTrending = () => {
  router.push('/trending')
}

// 移除不再需要的 navigateTo 函数
// const navigateTo = (path) => {
//   router.push(path);
// };

// 监听排序变化
watch(sortBy, () => {
  fetchSubscribedVideos() // 排序变化时重新获取第一页
})

// 组件挂载时获取数据
onMounted(() => {
  fetchSubscribedVideos() // 初始加载第一页
})
</script>

<style scoped>
.subscriptions-container {
  padding: 20px;
}

.profile-content {
  /* 如果需要，可以添加内边距 */
}

.content-wrapper {
  background-color: #fff; /* 可选：添加背景色 */
  padding: 20px;
  border-radius: 4px; /* 可选：添加圆角 */
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.sort-select {
  width: 120px;
}

.video-content {
  /* 可以添加最小高度以避免加载时闪烁 */
  min-height: 200px;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

.video-grid {
  display: grid;
  /* 根据需要调整列数和间距 */
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); /* 响应式列 */
  gap: 20px; /* 列和行之间的间距 */
}

.video-card {
  cursor: pointer;
  border: 1px solid #eee; /* 可选：添加边框 */
  border-radius: 4px;
  overflow: hidden; /* 防止内容溢出 */
  transition: box-shadow 0.3s ease;
}

.video-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.thumbnail {
  position: relative;
  width: 100%;
  padding-top: 56.25%; /* 16:9 aspect ratio */
  background-color: #f0f0f0; /* 图像加载时的占位符颜色 */
}

.thumbnail img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover; /* 保持宽高比并填充 */
}

.duration {
  position: absolute;
  bottom: 5px;
  right: 5px;
  background-color: rgba(0, 0, 0, 0.7);
  color: #fff;
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 12px;
}

.video-info {
  display: flex;
  padding: 10px;
}

.channel-avatar {
  margin-right: 10px;
}

.video-details {
  flex: 1;
  overflow: hidden; /* 防止长标题溢出 */
}

.title {
  font-size: 15px;
  font-weight: 500;
  margin: 0 0 5px 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.channel-name,
.stats {
  font-size: 13px;
  color: #606266;
  margin-bottom: 3px;
}

.stats {
  display: flex;
  align-items: center;
}

.dot {
  margin: 0 5px;
}

.load-more {
  text-align: center;
  margin-top: 30px;
}
</style>